
import { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { Progress } from "@/components/ui/progress";
import { Badge } from "@/components/ui/badge";
import { CheckCircle, ExternalLink, Users, Target, Lightbulb } from "lucide-react";

interface Question {
  id: string;
  text: string;
  category: 'realistic' | 'investigative' | 'artistic' | 'social' | 'enterprising' | 'conventional';
}

const questions: Question[] = [
  { id: "1", text: "I enjoy educational research or trying new pedagogical tools", category: "investigative" },
  { id: "2", text: "I feel fulfilled when helping peers improve their teaching", category: "social" },
  { id: "3", text: "I'm drawn to cross-disciplinary curriculum design", category: "artistic" },
  { id: "4", text: "I like organizing educational events or workshops", category: "enterprising" },
  { id: "5", text: "I prefer systematic approaches to lesson planning", category: "conventional" },
  { id: "6", text: "I enjoy hands-on teaching with manipulatives and tools", category: "realistic" },
  { id: "7", text: "I'm interested in analyzing student performance data", category: "investigative" },
  { id: "8", text: "I find mentoring new teachers rewarding", category: "social" },
  { id: "9", text: "I like creating visually appealing learning materials", category: "artistic" },
  { id: "10", text: "I enjoy leading curriculum committees", category: "enterprising" },
  { id: "11", text: "I prefer structured assessment methods", category: "conventional" },
  { id: "12", text: "I like building physical learning environments", category: "realistic" },
  { id: "13", text: "I'm drawn to educational theory and research", category: "investigative" },
  { id: "14", text: "I enjoy collaborating with students on projects", category: "social" },
  { id: "15", text: "I like incorporating creative arts into lessons", category: "artistic" },
  { id: "16", text: "I'm comfortable presenting to large groups", category: "enterprising" },
  { id: "17", text: "I value detailed record-keeping and documentation", category: "conventional" },
  { id: "18", text: "I enjoy teaching through laboratory or field work", category: "realistic" }
];

const riasecProfiles = {
  'Social-Investigative': {
    description: "You're drawn to educational research and mentoring fellow educators",
    percentages: { social: 45, investigative: 35, artistic: 20 },
    careers: [
      "Educational Researcher",
      "Mentor Coach", 
      "Professional Development Trainer",
      "Curriculum Specialist"
    ],
    skillPaths: [
      "Data-Driven Teaching Methods",
      "Educational Research & Analysis",
      "Peer Mentoring & Coaching",
      "Evidence-Based Instruction"
    ],
    communities: [
      "Educational Research Network",
      "Teacher Mentoring Circle",
      "Data in Education Community"
    ]
  },
  'Artistic-Social': {
    description: "You combine creativity with people-focused teaching approaches",
    percentages: { artistic: 40, social: 35, investigative: 25 },
    careers: [
      "Creative Curriculum Designer",
      "Arts Integration Specialist",
      "Community Education Coordinator",
      "Learning Experience Designer"
    ],
    skillPaths: [
      "Creative Curriculum Design",
      "Visual Learning Strategies",
      "Community Partnership Building",
      "Interdisciplinary Teaching"
    ],
    communities: [
      "Creative Education Network",
      "Arts in Education Group",
      "Community Learning Partners"
    ]
  },
  'Enterprising-Social': {
    description: "You're energized by leading educational initiatives and building communities",
    percentages: { enterprising: 40, social: 35, conventional: 25 },
    careers: [
      "Educational Leader",
      "Professional Development Coordinator",
      "School Innovation Director",
      "Educational Consultant"
    ],
    skillPaths: [
      "Educational Leadership",
      "Change Management in Education",
      "Professional Learning Design",
      "Strategic Planning"
    ],
    communities: [
      "Educational Leadership Circle",
      "Innovation in Schools Network",
      "Professional Development Community"
    ]
  },
  'Investigative-Conventional': {
    description: "You excel at systematic research and data-driven educational practices",
    percentages: { investigative: 45, conventional: 35, realistic: 20 },
    careers: [
      "Education Data Analyst",
      "Assessment Specialist",
      "Curriculum Research Coordinator",
      "Educational Technology Specialist"
    ],
    skillPaths: [
      "Educational Data Analysis",
      "Assessment Design & Implementation",
      "Research Methodology",
      "Technology Integration"
    ],
    communities: [
      "Education Analytics Group",
      "Assessment & Evaluation Network",
      "Educational Research Society"
    ]
  }
};

interface InterestExplorerAssessmentProps {
  onComplete: (result: string, description: string) => void;
  currentResult?: {
    status: string;
    result?: string;
    description?: string;
  };
}

export function InterestExplorerAssessment({ onComplete, currentResult }: InterestExplorerAssessmentProps) {
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [responses, setResponses] = useState<Record<string, boolean>>({});
  const [showResults, setShowResults] = useState(false);
  const [result, setResult] = useState<keyof typeof riasecProfiles | null>(null);

  const handleResponse = (questionId: string, value: boolean) => {
    setResponses(prev => ({ ...prev, [questionId]: value }));
  };

  const handleNext = () => {
    if (currentQuestion < questions.length - 1) {
      setCurrentQuestion(prev => prev + 1);
    } else {
      calculateResults();
    }
  };

  const handlePrevious = () => {
    if (currentQuestion > 0) {
      setCurrentQuestion(prev => prev - 1);
    }
  };

  const calculateResults = () => {
    const categoryScores = {
      realistic: 0,
      investigative: 0,
      artistic: 0,
      social: 0,
      enterprising: 0,
      conventional: 0
    };

    questions.forEach(question => {
      const response = responses[question.id];
      if (response === true) {
        categoryScores[question.category]++;
      }
    });

    // Find top three categories
    const sortedCategories = Object.entries(categoryScores)
      .sort(([,a], [,b]) => b - a)
      .slice(0, 3)
      .map(([category]) => category);

    // Determine profile based on top categories
    const topTwo = sortedCategories.slice(0, 2).sort().join('-');
    const profileMap: Record<string, keyof typeof riasecProfiles> = {
      'investigative-social': 'Social-Investigative',
      'artistic-social': 'Artistic-Social',
      'enterprising-social': 'Enterprising-Social',
      'conventional-investigative': 'Investigative-Conventional'
    };

    const profile = profileMap[topTwo] || 'Social-Investigative';
    setResult(profile);
    setShowResults(true);
  };

  const handleComplete = () => {
    if (result) {
      const resultData = riasecProfiles[result];
      onComplete(`${result} Profile`, resultData.description);
    }
  };

  const progress = ((currentQuestion + 1) / questions.length) * 100;
  const answeredQuestions = Object.keys(responses).length;

  if (showResults && result) {
    const resultData = riasecProfiles[result];
    
    return (
      <div className="space-y-6">
        <Card className="bg-gradient-to-r from-orange-50 to-yellow-50 border-orange-200">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <CheckCircle className="w-5 h-5 text-green-600" />
              Your Interest Profile: {result}
            </CardTitle>
            <CardDescription>{resultData.description}</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div>
                <h4 className="font-medium mb-3">Interest Distribution</h4>
                <div className="space-y-2">
                  {Object.entries(resultData.percentages).map(([category, percentage]) => (
                    <div key={category} className="flex items-center gap-3">
                      <span className="text-sm font-medium w-20 capitalize">{category}</span>
                      <div className="flex-1">
                        <Progress value={percentage} className="h-2" />
                      </div>
                      <span className="text-sm font-medium">{percentage}%</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        <div className="grid md:grid-cols-3 gap-4">
          {/* Career Roles */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center gap-2">
                <Target className="w-5 h-5" />
                Career Roles
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {resultData.careers.map((career, index) => (
                  <Badge key={index} variant="outline" className="w-full justify-start p-2 text-xs">
                    {career}
                  </Badge>
                ))}
              </div>
            </CardContent>
          </Card>

          {/* Skill Growth Paths */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center gap-2">
                <Lightbulb className="w-5 h-5" />
                Skill Growth Paths
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {resultData.skillPaths.map((path, index) => (
                  <Button 
                    key={index} 
                    variant="outline" 
                    size="sm" 
                    className="w-full justify-start text-xs h-auto py-2"
                  >
                    <ExternalLink className="w-3 h-3 mr-2" />
                    {path}
                  </Button>
                ))}
              </div>
            </CardContent>
          </Card>

          {/* Communities */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg flex items-center gap-2">
                <Users className="w-5 h-5" />
                Suggested Communities
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-2">
                {resultData.communities.map((community, index) => (
                  <Button 
                    key={index} 
                    variant="outline" 
                    size="sm" 
                    className="w-full justify-start text-xs h-auto py-2"
                  >
                    <Users className="w-3 h-3 mr-2" />
                    {community}
                  </Button>
                ))}
              </div>
            </CardContent>
          </Card>
        </div>
        
        <div className="flex justify-center">
          <Button onClick={handleComplete} className="px-8">
            Save Results
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Progress */}
      <div className="space-y-2">
        <div className="flex justify-between text-sm">
          <span>Question {currentQuestion + 1} of {questions.length}</span>
          <span>{answeredQuestions} answered</span>
        </div>
        <Progress value={progress} className="h-2" />
      </div>

      {/* Question */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg">
            {questions[currentQuestion].text}
          </CardTitle>
          <CardDescription>
            Choose whether this statement applies to you
          </CardDescription>
        </CardHeader>
        <CardContent>
          <RadioGroup
            value={responses[questions[currentQuestion].id]?.toString() || ""}
            onValueChange={(value) => handleResponse(questions[currentQuestion].id, value === 'true')}
          >
            <div className="flex items-center space-x-2 p-3 rounded-lg hover:bg-accent/50 transition-colors">
              <RadioGroupItem value="true" id="yes" />
              <Label htmlFor="yes" className="flex-1 cursor-pointer font-medium">
                Yes, this applies to me
              </Label>
            </div>
            <div className="flex items-center space-x-2 p-3 rounded-lg hover:bg-accent/50 transition-colors">
              <RadioGroupItem value="false" id="no" />
              <Label htmlFor="no" className="flex-1 cursor-pointer font-medium">
                No, this doesn't apply to me
              </Label>
            </div>
          </RadioGroup>
        </CardContent>
      </Card>

      {/* Navigation */}
      <div className="flex justify-between">
        <Button 
          variant="outline" 
          onClick={handlePrevious}
          disabled={currentQuestion === 0}
        >
          Previous
        </Button>
        
        <Button 
          onClick={handleNext}
          disabled={responses[questions[currentQuestion].id] === undefined}
        >
          {currentQuestion === questions.length - 1 ? 'View Results' : 'Next'}
        </Button>
      </div>
    </div>
  );
}
